<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入员工姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input
          v-model="queryParams.gender"
          placeholder="请输入性别"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话号码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入职日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeBeginDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="工号" prop="workID">
        <el-input
          v-model="queryParams.workID"
          placeholder="请输入工号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['employee:employee:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['employee:employee:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['employee:employee:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['employee:employee:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工编号" align="center" prop="id" />
      <el-table-column label="员工姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthday" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号" align="center" prop="idCard" />
      <el-table-column label="婚姻状况" align="center" prop="wedlock">
        <template #default="scope">
          <dict-tag :options="sys_marriage" :value="scope.row.wedlock" />
        </template>
      </el-table-column>
      <el-table-column label="民族" align="center" prop="nationId">
        <template #default="scope">
          <dict-tag :options="sys_nation" :value="scope.row.nationId" />
        </template>
      </el-table-column>
      <el-table-column label="籍贯" align="center" prop="nativePlace" />
      <el-table-column label="政治面貌" align="center" prop="politicId">
        <template #default="scope">
          <dict-tag :options="sys_politics_status" :value="scope.row.politicId" />
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="电话号码" align="center" prop="phone" />
      <el-table-column label="联系地址" align="center" prop="address" />
      <el-table-column label="所属部门" align="center" prop="dept.deptName" />
      <el-table-column label="岗位" align="center" prop="posId">
        <template #default="scope">
          <span>{{ getPostName(scope.row.posId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="聘用形式" align="center" prop="engageForm" />
      <el-table-column label="最高学历" align="center" prop="tiptopDegree">
        <template #default="scope">
          <dict-tag :options="sys_degree" :value="scope.row.tiptopDegree" />
        </template>
      </el-table-column>
      <el-table-column label="所属专业" align="center" prop="specialty" />
      <el-table-column label="毕业院校" align="center" prop="school" />
      <el-table-column label="入职日期" align="center" prop="beginDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="在职状态" align="center" prop="workState" />
      <el-table-column label="工号" align="center" prop="workID" />
      <el-table-column label="合同期限" align="center" prop="contractTerm" />
      <el-table-column label="转正日期" align="center" prop="conversionTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.conversionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="离职日期" align="center" prop="notWorkDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.notWorkDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同起始日期" align="center" prop="beginContract" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.beginContract, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同终止日期" align="center" prop="endContract" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endContract, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工龄" align="center" prop="workAge" />
      <el-table-column label="工作经历" align="center" prop="workExperience" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['employee:employee:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['employee:employee:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工管理对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="employeeRef" :model="form" :rules="rules" label-width="100px">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="员工姓名" prop="name">
                  <el-input v-model="form.name" placeholder="请输入员工姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                    <el-option
                      v-for="dict in sys_user_sex"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birthday">
                  <el-date-picker clearable
                    v-model="form.birthday"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择出生日期"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="form.idCard" placeholder="请输入身份证号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="民族" prop="nationId">
                  <el-select v-model="form.nationId" placeholder="请选择民族" style="width: 100%">
                    <el-option
                      v-for="dict in sys_nation"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="婚姻状况" prop="wedlock">
                  <el-select v-model="form.wedlock" placeholder="请选择婚姻状况" style="width: 100%">
                    <el-option
                      v-for="dict in sys_marriage"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="政治面貌" prop="politicId">
                  <el-select v-model="form.politicId" placeholder="请选择政治面貌" style="width: 100%">
                    <el-option
                      v-for="dict in sys_politics_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="籍贯" prop="nativePlace">
                  <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="联系方式" name="contact">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电话号码" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入电话号码" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="联系地址" prop="address">
                  <el-input v-model="form.address" placeholder="请输入联系地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="工作信息" name="work">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="所属部门" prop="departmentId">
                  <el-tree-select
                    v-model="form.departmentId"
                    :data="enabledDeptOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }"
                    value-key="id"
                    placeholder="请选择所属部门"
                    clearable
                    check-strictly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位ID" prop="posId">
                  <el-input v-model="form.posId" placeholder="请输入职位ID" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="聘用形式" prop="engageForm">
                  <el-input v-model="form.engageForm" placeholder="请输入聘用形式" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工号" prop="workID">
                  <el-input v-model="form.workID" placeholder="请输入工号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入职日期" prop="beginDate">
                  <el-date-picker clearable
                    v-model="form.beginDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择入职日期"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="在职状态" prop="workState">
                  <el-input v-model="form.workState" placeholder="请输入在职状态" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="教育背景" name="education">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最高学历" prop="tiptopDegree">
                  <el-select v-model="form.tiptopDegree" placeholder="请选择最高学历" style="width: 100%">
                    <el-option
                      v-for="dict in sys_degree"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属专业" prop="specialty">
                  <el-input v-model="form.specialty" placeholder="请输入所属专业" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="毕业院校" prop="school">
                  <el-input v-model="form.school" placeholder="请输入毕业院校" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="合同信息" name="contract">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同期限" prop="contractTerm">
                  <el-input v-model="form.contractTerm" placeholder="请输入合同期限">
                    <template #append>年</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工龄" prop="workAge">
                  <el-input v-model="form.workAge" placeholder="请输入工龄">
                    <template #append>年</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="转正日期" prop="conversionTime">
                  <el-date-picker clearable
                    v-model="form.conversionTime"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择转正日期"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="离职日期" prop="notWorkDate">
                  <el-date-picker clearable
                    v-model="form.notWorkDate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择离职日期"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同起始日期" prop="beginContract">
                  <el-date-picker clearable
                    v-model="form.beginContract"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择合同起始日期"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同终止日期" prop="endContract">
                  <el-date-picker clearable
                    v-model="form.endContract"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择合同终止日期"
                    style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <el-tab-pane label="工作经历" name="experience">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="工作经历" prop="workExperience">
                  <el-input v-model="form.workExperience" type="textarea" placeholder="请输入工作经历" :rows="4" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Employee">
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee } from "@/api/employee/employee"
import { listDept } from "@/api/system/dept"
import { deptTreeSelect } from "@/api/system/user"
import { listPost } from "@/api/employee/post"

const { proxy } = getCurrentInstance()
const { sys_marriage, sys_user_sex, sys_degree, sys_nation, sys_politics_status } = proxy.useDict('sys_marriage', 'sys_user_sex', 'sys_degree', 'sys_nation', 'sys_politics_status')

const employeeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeBeginDate = ref([])
const activeTab = ref("basic")
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const postOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    gender: null,
    idCard: null,
    phone: null,
    beginDate: null,
    workID: null,
  },
  rules: {
    name: [{ required: true, message: "员工姓名不能为空", trigger: "blur" }],
    // gender: [{ required: true, message: "性别不能为空", trigger: "change" }],
    // idCard: [
    //   { required: true, message: "身份证号不能为空", trigger: "blur" },
    //   // { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: "请输入正确的身份证号码", trigger: "blur" },
    //   // { min: 18, max: 18, message: "身份证号码必须为18位", trigger: "blur" }
    //   { min: 18, max: 18, message: "请输入正确的身份证号", trigger: "blur" }
    // ],
    // nationId: [{ required: true, message: "民族不能为空", trigger: "change" }],
    // politicId: [{ required: true, message: "政治面貌不能为空", trigger: "change" }],
    // email: [
    //   { required: true, message: "邮箱不能为空", trigger: "blur" },
    //   { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
    // ],
    phone: [
      { required: true, message: "电话号码不能为空", trigger: "blur" },
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" },
      { min: 11, max: 11, message: "手机号码必须为11位", trigger: "blur" }
    ],
    departmentId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
    // posId: [{ required: true, message: "岗位不能为空", trigger: "change" }],
    // tiptopDegree: [{ required: true, message: "最高学历不能为空", trigger: "change" }],
    // specialty: [{ required: true, message: "所属专业不能为空", trigger: "blur" }],
    // school: [{ required: true, message: "毕业院校不能为空", trigger: "blur" }]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询员工管理列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeBeginDate && '' != daterangeBeginDate) {
    queryParams.value.params["beginBeginDate"] = daterangeBeginDate.value[0]
    queryParams.value.params["endBeginDate"] = daterangeBeginDate.value[1]
  }
  listEmployee(queryParams.value).then(response => {
    employeeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    gender: null,
    birthday: null,
    idCard: null,
    wedlock: null,
    nationId: null,
    nativePlace: null,
    politicId: null,
    email: null,
    phone: null,
    address: null,
    departmentId: null,
    posId: null,
    engageForm: null,
    tiptopDegree: null,
    specialty: null,
    school: null,
    beginDate: null,
    workState: null,
    workID: null,
    contractTerm: null,
    conversionTime: null,
    notWorkDate: null,
    beginContract: null,
    endContract: null,
    workAge: null,
    workExperience: null
  }
  proxy.resetForm("employeeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeBeginDate.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加员工管理"
  getDeptTree()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getEmployee(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改员工管理"
    getDeptTree()
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["employeeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateEmployee(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEmployee(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除员工管理编号为"' + _ids + '"的数据项？').then(function() {
    return delEmployee(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('employee/employee/export', {
    ...queryParams.value
  }, `employee_${new Date().getTime()}.xlsx`)
}

/** 根据部门ID获取部门名称 */
function getDeptName(deptId) {
  if (!deptId) return '';
  return '';
}

/** 递归查找部门 */
function findDeptById(deptList, deptId) {
  if (!deptList) return null;
  for (let i = 0; i < deptList.length; i++) {
    const dept = deptList[i];
    if (dept.id === deptId) {
      return dept;
    }
    if (dept.children && dept.children.length) {
      const found = findDeptById(dept.children, deptId);
      if (found) return found;
    }
  }
  return null;
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 查询岗位列表 */
function getPostList() {
  listPost({}).then(response => {
    postOptions.value = response.rows
  })
}

/** 根据岗位ID获取岗位名称 */
function getPostName(postId) {
  if (!postId) return ''
  const post = postOptions.value.find(item => item.postId === postId)
  return post ? post.postName : ''
}

/** 根据最高学历获取对应的值 */
function getDegreeValue(degree) {
  const dict = sys_degree.value.find(item => item.label === degree)
  return dict ? dict.value : ''
}

onMounted(() => {
  getList()
  getDeptTree()
  getPostList()
})
</script>